/**
 * 表格分页器
 * author Forjune
 * @param {Number} total 总条数
 */
import React, { useState, useEffect } from "react";
import { Pagination, ConfigProvider, Input, message } from 'antd'
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import './index.styl'

function Paging({ pageSize, total, handlePageChange, pageCount, pages }) {
  const [page, setPage] = useState(1)
  const [value, setvalue] = useState(pageCount)
  const onChange = (page, pageSize) => {
    setPage(page)
    handlePageChange(page, pageSize)
  }
  const handleGo = () => {
    // 正整数的正则表达式
    let reg = /(^[1-9]\d*$)/
    if (reg.test(value)) {
      let num = Number(value)
      if (num > Math.ceil(total / pageSize)) {
        setPage(Math.ceil(total / pageSize))
        handlePageChange(Math.ceil(total / pageSize), pageSize)
      } else {
        setPage(num)
        handlePageChange(num, pageSize)
      }
    } else {
      message.warning('请输入正确的页数')
    }
  }
  const handleOnChange = (e) => {
    setvalue(e.target.value)
  }

  useEffect(() => {
    setPage(pageCount)
    setvalue(pageCount)
  }, [pageCount])

  return (
    <ConfigProvider locale={zh_CN}>
      <div style={{ display: pages === 1 || pages === 0 ? 'none' : 'block' }}>
        <div className="paging">
          <span className="page-btn" onClick={() => handlePageChange(1,pageSize)}>首页</span>
          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            pageSizeOptions={['10']}
            onChange={onChange}
          />
          <span className="page-btn last-page-btn" onClick={() => handlePageChange(Math.ceil(total / pageSize), pageSize)}>尾页</span>
          <div className="paging-jump">
            <span>跳转到</span>
            <Input onChange={handleOnChange} className="self-input" value={value} />
            <span>页</span>
          </div>
          <div className="go" onClick={handleGo}>GO</div>
          <div className="paging-total">
            <span>共{Math.ceil(total / pageSize) || 0}页/</span>
            <span>{total || 0}条数据</span>
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
}

export default Paging
